const GroupChat = require('../models/groupChat');
const User = require('../models/user');
const { validationResult } = require('express-validator');

const groupController = {
    async createGroup(req, res, next) {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ errors: errors.array() });
        }

        const { name, user_ids } = req.body;

        try {
            for (const user_id of user_ids) {
                const user = await User.findById(user_id);
                if (!user) {
                    return res.status(404).json({ error: `User ${user_id} not found` });
                }
            }

            const { group_id } = await GroupChat.create({
                name,
                user_ids: [...user_ids, req.user.user_id]
            });
            res.status(201).json({ group_id });
        } catch (error) {
            next(error);
        }
    },

    async sendMessage(req, res, next) {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ errors: errors.array() });
        }

        const { content } = req.body;

        try {
            const { message_id } = await GroupChat.createMessage({
                group_id: req.params.group_id,
                user_id: req.user.user_id,
                content
            });
            res.status(201).json({ message_id });
        } catch (error) {
            next(error);
        }
    },

    async getMessages(req, res, next) {
        const { limit = 20, offset = 0 } = req.query;

        try {
            const messages = await GroupChat.findMessages(req.params.group_id, parseInt(limit), parseInt(offset));
            res.json(messages);
        } catch (error) {
            next(error);
        }
    }
};

module.exports = groupController;